#include "AssetManager.h"
#include <algorithm>

AssetManager* AssetManager::s_instance = nullptr;

AssetManager* AssetManager::GetInstance()
{
    if (!s_instance)
        s_instance = new AssetManager();
    return s_instance;
}

void AssetManager::RegisterLoadCallback(AssetLoadCallback callback)
{
    m_loadCallbacks.push_back(callback);
}

std::shared_ptr<Asset> AssetManager::GetAsset(const std::string& id) const
{
    auto it = m_assets.find(id);
    if (it != m_assets.end())
        return it->second;
    return nullptr;
}

bool AssetManager::HasAsset(const std::string& id) const
{
    return m_assets.find(id) != m_assets.end();
}

bool AssetManager::LoadAsset(const std::string& id)
{
    auto asset = GetAsset(id);
    if (!asset)
        return false;

    bool success = asset->Load();
    NotifyLoadStatus(id, success);
    return success;
}

void AssetManager::UnloadAsset(const std::string& id)
{
    auto asset = GetAsset(id);
    if (asset)
        asset->Unload();
}

bool AssetManager::LoadAllAssets()
{
    bool allSuccess = true;

    for (auto& pair : m_assets)
    {
        bool success = pair.second->Load();
        NotifyLoadStatus(pair.first, success);

        if (!success)
            allSuccess = false;
    }

    return allSuccess;
}

void AssetManager::UnloadAllAssets()
{
    for (auto& pair : m_assets)
    {
        pair.second->Unload();
    }
}

std::vector<std::shared_ptr<Asset>> AssetManager::GetAssetsByType(AssetType type) const
{
    std::vector<std::shared_ptr<Asset>> result;

    for (auto& pair : m_assets)
    {
        if (pair.second->GetType() == type)
            result.push_back(pair.second);
    }

    return result;
}

void AssetManager::GarbageCollect()
{
    // 这里可以实现一些资源垃圾回收逻辑
    // 比如移除长时间未使用的资源
}

void AssetManager::NotifyLoadStatus(const std::string& id, bool success)
{
    for (auto& callback : m_loadCallbacks)
    {
        callback(id, success);
    }
}
